from django.core.management.base import BaseCommand
from core.models import Advertisement
import os
import shutil
from django.conf import settings
import logging

logger = logging.getLogger(__name__)

class Command(BaseCommand):
    help = '修复广告图片路径问题，解决嵌套ads目录和路径不正确的问题'

    def handle(self, *args, **options):
        # 确保ads目录存在
        ads_dir = os.path.join(settings.MEDIA_ROOT, 'ads')
        if not os.path.exists(ads_dir):
            os.makedirs(ads_dir)
            self.stdout.write(self.style.SUCCESS(f'创建ads目录: {ads_dir}'))
        
        # 检查默认广告图片是否存在
        default_ad_path = os.path.join(ads_dir, 'default-ad.jpg')
        if not os.path.exists(default_ad_path):
            self.stdout.write(self.style.WARNING(f'默认广告图片不存在: {default_ad_path}'))
        
        # 获取所有广告
        ads = Advertisement.objects.all()
        self.stdout.write(f'开始处理 {ads.count()} 个广告...')
        fixed_count = 0
        
        for ad in ads:
            self.stdout.write(f'处理广告 ID: {ad.pk}, 标题: {ad.title}')
            
            if ad.image:
                original_path = ad.image.name
                
                # 修复嵌套路径问题
                if 'ads/ads/' in original_path:
                    ad.image.name = original_path.replace('ads/ads/', 'ads/')
                    self.stdout.write(f'  修复嵌套路径: {original_path} -> {ad.image.name}')
                
                # 确保路径以ads/开头
                if not ad.image.name.startswith('ads/'):
                    ad.image.name = f'ads/{ad.image.name}'
                    self.stdout.write(f'  修正图片路径: {ad.image.name}')
                
                # 检查图片文件是否存在
                image_path = os.path.join(settings.MEDIA_ROOT, ad.image.name)
                if not os.path.exists(image_path):
                    self.stdout.write(self.style.WARNING(f'  图片路径不存在: {image_path}'))
                    
                    # 尝试查找可能的路径
                    possible_paths = [
                        os.path.join(settings.MEDIA_ROOT, os.path.basename(ad.image.name)),
                        os.path.join(settings.MEDIA_ROOT, original_path),
                        os.path.join(settings.MEDIA_ROOT, 'ads', os.path.basename(ad.image.name))
                    ]
                    
                    found = False
                    for possible_path in possible_paths:
                        if os.path.exists(possible_path) and possible_path != image_path:
                            # 复制文件到正确位置
                            os.makedirs(os.path.dirname(image_path), exist_ok=True)
                            shutil.copy(possible_path, image_path)
                            self.stdout.write(self.style.SUCCESS(f'  图片已从 {possible_path} 复制到 {image_path}'))
                            found = True
                            break
                    
                    if not found and os.path.exists(default_ad_path):
                        # 如果找不到原始图片，使用默认图片
                        shutil.copy(default_ad_path, image_path)
                        self.stdout.write(self.style.WARNING(f'  使用默认广告图片: {image_path}'))
                
                # 保存广告
                ad.save()
                fixed_count += 1
                self.stdout.write(self.style.SUCCESS(f'  成功修复广告图片: {ad.title}'))
            else:
                self.stdout.write(self.style.WARNING(f'  广告没有图片: {ad.title}'))
        
        self.stdout.write(self.style.SUCCESS(f'成功修复 {fixed_count} 个广告图片!')) 